#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
客户分析函数模块
提供客户价值计算、分层、策略生成等功能
独立于main.py的数据加载和模型训练逻辑
"""

from config import (
    VALUE_WEIGHTS, VALUE_THRESHOLDS, RISK_THRESHOLDS, ADJUSTMENT_FACTORS
)

def calculate_customer_value(row):
    """优化的客户价值计算（多维度评估）"""
    try:
        # 基础价值计算
        base_value = (
            row['余额'] * VALUE_WEIGHTS['balance_weight'] + 
            row['估计薪水'] * VALUE_WEIGHTS['salary_weight'] + 
            row['银行产品编号'] * VALUE_WEIGHTS['products_multiplier'] * VALUE_WEIGHTS['products_weight']
        )
        
        # 调整因子
        adjustment_factor = 1.0
        
        # 信用分调整
        if row['信用分'] > ADJUSTMENT_FACTORS['credit_score_high']:
            adjustment_factor += ADJUSTMENT_FACTORS['credit_adjustment']
        elif row['信用分'] < ADJUSTMENT_FACTORS['credit_score_low']:
            adjustment_factor -= ADJUSTMENT_FACTORS['credit_adjustment']
        
        # 活跃成员调整
        if row['活跃成员'] == 1:
            adjustment_factor += ADJUSTMENT_FACTORS['active_adjustment']
        
        # 信用卡调整
        if row['信用卡'] == 1:
            adjustment_factor += ADJUSTMENT_FACTORS['card_adjustment']
        
        # 任期调整
        if row['任期'] > ADJUSTMENT_FACTORS['tenure_threshold']:
            adjustment_factor += ADJUSTMENT_FACTORS['tenure_adjustment']
        
        final_value = base_value * adjustment_factor
        return max(0, final_value)  # 确保价值非负
        
    except Exception as e:
        print(f"客户价值计算错误: {e}")
        return 0

def value_stratification(value):
    """客户价值分层"""
    if value > VALUE_THRESHOLDS['high_value']:
        return '高价值'
    elif value > VALUE_THRESHOLDS['medium_value']:
        return '中价值'
    else:
        return '低价值'

def generate_strategy(row):
    """基于风险-价值矩阵的干预策略生成"""
    # 根据配置的阈值确定风险等级
    risk_probability = row['流失概率'] / 100  # 转换为小数
    if risk_probability > RISK_THRESHOLDS['high_risk']:
        risk_level = '高风险'
    elif risk_probability > RISK_THRESHOLDS['medium_risk']:
        risk_level = '中风险'
    else:
        risk_level = '低风险'
    
    # 基于风险-价值矩阵的干预策略
    strategy_matrix = {
        '高风险-高价值': '专属客户经理一对一服务; 定制化产品方案; 紧急挽留计划',
        '高风险-中价值': '发送个性化挽留邮件; 提供产品升级优惠; 电话回访',
        '高风险-低价值': '自动化营销活动; 提供基础产品优惠; 短信关怀',
        '中风险-高价值': '定期关怀电话; 推荐高端理财产品; VIP服务升级',
        '中风险-中价值': '提供高息定期存款产品; 邀请参加会员互动活动',
        '中风险-低价值': '发送产品推荐邮件; 提供新客户优惠',
        '低风险-高价值': '维持现有服务水平; 推荐增值服务; 定期满意度调研',
        '低风险-中价值': '推荐适合的理财产品; 邀请参加金融讲座',
        '低风险-低价值': '保持基础服务; 适时推送优惠信息'
    }
    
    strategy_key = f"{risk_level}-{row['价值分层']}"
    return strategy_matrix.get(strategy_key, '标准客户服务')

def generate_attribute_strategy(row):
    """生成属性改善建议"""
    suggestions = []
    
    # 余额相关建议
    if row['余额'] == 0:
        suggestions.append('紧急关注：零余额客户，建议立即联系了解情况')
    elif row['余额'] < 10000:
        suggestions.append('提供高息定期存款产品，鼓励增加存款')
    elif row['余额'] > 200000:
        suggestions.append('推荐高端理财产品和投资咨询服务')
    
    # 产品数量建议
    if row['银行产品编号'] == 1:
        suggestions.append('推荐附加产品：信用卡、理财产品或保险')
    elif row['银行产品编号'] >= 4:
        suggestions.append('产品整合建议：优化产品组合，提供一站式服务')
    
    # 活跃状态建议
    if row['活跃成员'] == 0:
        suggestions.append('激活策略：邀请参加会员互动活动，提供专属优惠')
    
    # 任期建议
    if row['任期'] < 2:
        suggestions.append('新客户关怀：提供入门指导和专属新客户优惠')
    elif row['任期'] > 10:
        suggestions.append('忠诚客户奖励：提供长期客户专属权益和感谢礼品')
    
    # 信用分建议
    if row['信用分'] < 600:
        suggestions.append('信用提升建议：提供信用咨询服务，推荐信用建设产品')
    elif row['信用分'] > 750:
        suggestions.append('优质信用客户：推荐高端信贷产品和投资机会')
    
    # 信用卡建议
    if row['信用卡'] == 0:
        suggestions.append('信用卡推荐：根据客户资质推荐合适的信用卡产品')
    
    # 年龄相关建议
    age = row['年龄']
    if age < 30:
        suggestions.append('年轻客户专属：推荐储蓄计划和投资入门产品')
    elif age > 55:
        suggestions.append('成熟客户服务：推荐稳健理财和退休规划产品')
    
    return suggestions if suggestions else ['维持现有服务水平']

def calculate_simple_churn_probability(customer_row):
    """
    简化的流失概率计算（启发式方法）
    实际应用中应使用训练好的机器学习模型
    """
    score = 0.0
    
    # 年龄因子
    age = customer_row['年龄']
    if age < 25 or age > 60:
        score += 0.2
    elif 25 <= age <= 35:
        score += 0.1
    
    # 余额因子
    balance = customer_row['余额']
    if balance == 0:
        score += 0.3
    elif balance < 50000:
        score += 0.15
    elif balance > 200000:
        score -= 0.1
    
    # 产品数量因子
    products = customer_row['银行产品编号']
    if products == 1:
        score += 0.2
    elif products >= 4:
        score += 0.1
    else:
        score -= 0.05
    
    # 活跃状态因子
    if customer_row['活跃成员'] == 0:
        score += 0.25
    
    # 信用卡因子
    if customer_row['信用卡'] == 0:
        score += 0.1
    
    # 信用分因子
    credit_score = customer_row['信用分']
    if credit_score < 600:
        score += 0.2
    elif credit_score > 750:
        score -= 0.1
    
    # 任期因子
    tenure = customer_row['任期']
    if tenure < 2:
        score += 0.15
    elif tenure > 8:
        score -= 0.1
    
    # 确保概率在0-1之间
    probability = max(0.0, min(1.0, score))
    return probability